<template>
  <div class="box">
    <RouteTitle isBack />
    <div class="content">
      <a-row justify="space-between" align="middle">
        <a-col>充值类型：</a-col>
        <a-col
          @click="ruleClick"
          style="color: var(--ss-primary-color); cursor: pointer"
          ><search-outlined />查看消耗规则</a-col
        >
      </a-row>
      <a-row align="middle" class="recharge-type">
        <a-col
          class="recharge-item"
          v-for="item in rechargeList"
          :key="item.type"
          @click="rechargeClick(item)"
          :class="rechargeKey == item.type ? 'recharge-bg' : ''"
        >
          <div class="item-text">{{ item.type_text }}</div>
          <div :class="rechargeKey == item.type ? 'checked' : ''">
            <check-outlined :rotate="300" v-if="rechargeKey == item.type" />
          </div>
        </a-col>
      </a-row>
      <a-row justify="space-between" align="middle" v-if="rechargeKey !== 1">
        <a-col>充值选项：</a-col>
      </a-row>
      <a-row align="middle" class="recharge-type" v-if="rechargeKey !== 1">
        <a-col
          class="recharge-item"
          v-for="item in rechargeOptions"
          :key="item.id"
          @click="rechargeSelectClick(item)"
          :class="rechargeSelect == item.id ? 'recharge-bg' : ''"
        >
          <div class="item-text" v-if="!item.custom">
            <div class="text" v-if="item.video_num">{{ item.video_num }}条</div>
            <div class="text" v-if="item.art_num">{{ item.art_num }}次</div>
            <div class="text">
              <!-- <span>{{ item.creation_num }}次</span> -->
              <span style="font-size: 14px" v-if="item.words_num"
                >{{ item.words_num }} 字数</span
              >
            </div>
            <div class="amount">{{ item.money }}</div>
          </div>
          <div :class="rechargeSelect == item.id ? 'checked' : ''">
            <check-outlined :rotate="300" v-if="rechargeSelect == item.id" />
          </div>
        </a-col>
      </a-row>
      <div v-if="rechargeKey == 1">
        <div class="purchase-quantity">购买容量:</div>
        <div class="voucher-number">
          <a-row>
            <a-col
              class="voucher-item"
              :class="RAMItem == item ? 'voucher-border' : ''"
              v-for="(item, index) in RAMList"
              :key="index"
              @click="RAMClick(item)"
              >{{ item }}G

              <div :class="RAMItem == item ? 'checked' : ''">
                <check-outlined :rotate="300" v-if="RAMItem == item" />
              </div>
            </a-col>
          </a-row>
        </div>
        <div class="purchase-quantity" v-if="validityList.length">有效期：</div>
        <div class="period-validity" v-if="validityList.length">
          <a-row class="validity-list">
            <a-col
              class="item"
              v-for="item in validityList"
              :class="validityData.id == item.id ? 'item-broder' : ''"
              :key="item.id"
              :style="{
                borderLeft:
                  validityData.id == item.id
                    ? '1px solid #ff6562'
                    : '1px solid #e0e0e6',
                borderRight:
                  validityData.id == item.id
                    ? '1px solid #ff6562'
                    : '1px solid #e0e0e6',
              }"
              @click="validityClick(item)"
              >{{ item.capacity_day_text }}</a-col
            >
          </a-row>
        </div>
        <div
          class="purchase-quantity"
          style="margin-bottom: 0"
          v-if="validityList.length"
        >
          金额：
        </div>
        <div
          style="font-size: 24px; color: var(--ss-primary-color)"
          v-if="validityList.length"
        >
          ￥{{ validityData.money || 0.0 }}
        </div>
      </div>
      <div>
		<a-popover placement="top" v-if="rechargeObj?.can_pay == 0 && rechargeObj?.pay_not_msg" trigger="click">
			<template #content>
				{{rechargeObj?.pay_not_msg}}
			</template>
			<a-button :disabled="rechargeObj?.can_pay == 0">确认充值</a-button>
		</a-popover>
        <a-button
			v-else
          type="primary"
          style="margin-top: 10px; border-radius: 5px"
          @click="handleRecharge"
          :disabled="btnDisable"
          :loading="loading"
          >确认充值</a-button
        >
      </div>
    </div>

    <!-- 规则弹框 -->
    <a-modal v-model:visible="visible" :footer="null">
      <template #title>
        <span style="font-size: 18px">消耗规则</span>
      </template>
      <p>
        视频条数：当发布剪辑任务时，会扣除剪辑视频数量相应的剪辑条数；若剪辑失败，则会返还失败的剪辑任务中相应的剪辑条数
      </p>
      <!-- <p>
        任务金：当发布达人任务时，会扣除任务相应的预算；当达人完成任务时，将会从扣除的任务预算中结算给达人；当任务完成/结束后，未使用的任务预算将会返还
      </p> -->
      <p>AI创作字数：每次生成内容，会扣除对应创作字数</p>
    </a-modal>
  </div>

  <memberShip
    :rechargeData="rechargeData"
    :visible="showMemberShip"
    @close="handleClose"
  />
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  watch,
  computed,
  onMounted,
} from "vue";
import {
  SearchOutlined,
  CheckOutlined,
  LineOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import request from "../../../common/utils/request";
import memberShip from "./modules/memberShip.vue";
import { message } from "ant-design-vue";
import store from '@/store';
export default defineComponent({
  name: "VoucherCenter",
  components: {
    SearchOutlined,
    CheckOutlined,
    LineOutlined,
    PlusOutlined,
    memberShip,
  },
  setup() {
    // 路由
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      count: 0,
      visible: false,
      rechargeKey: route.query.key ? Number(route.query.key) : 0,
      rechargeList: [],
      rechargeOptions: [],
	  rechargeObj: {},
      rechargeSelect: "",
      amountNum: "",
      textColorChange: false,
      validityList: [],
      validityData: {},
      capacityList: [],
      RAMList: [],
      RAMItem: null,
      showMemberShip: false,
      rechargeData: {},
      loading: false,
      btnDisable: true,
    });

    const getRechargeDetail = () => {
      request.get("/work_ai", "/user/socialMedia/pointCoinPackage/get").then((res) => {
        state.rechargeList = res.result;
		state.rechargeObj = res.result[0]
        state.rechargeOptions = res?.result[0]?.item;

        // 从素材库(成片库)里扩容 进来的时候
        if (route.query.key) {
          rechargeClick({ type: Number(route.query.key) });
        }
      });
    };

    // 内存选择
    const RAMClick = (data) => {
      state.btnDisable = true;
      state.RAMItem = data;
      state.validityList = state.capacityList
        .filter((item) => item.capacity == data)
        .sort((a, b) => a.capacity_day - b.capacity_day);
      state.validityData = {};
    };

    const ruleClick = () => {
      state.visible = true;
    };

    const blurChange = () => {
      state.textColorChange = true;
    };

    const focusChange = () => {
      state.textColorChange = false;
    };

    const handleClose = () => {
      state.showMemberShip = false;
    };

    const validityClick = (item) => {
      state.btnDisable = false;
      state.validityData = { ...item };

      Object.assign(state.rechargeData, {
        validityData: item,
      });
    };

    const rechargeClick = (item) => {
      state.rechargeKey = item.type;
      state.btnDisable = true;
      state.rechargeSelect = "";
      state.validityList = [];
      state.validityData = {};
      state.RAMItem = null;
      state.rechargeOptions = state.rechargeList.find(
        (item) => item.type == state.rechargeKey
      ).item;
	  state.rechargeObj = state.rechargeList.find(
        (item) => item.type == state.rechargeKey
      )
      if (item.type == 1) {
        state.capacityList = state.rechargeList.find(
          (item) => item.type == state.rechargeKey
        ).item;
        state.RAMList = [
          ...new Set(state.capacityList.map((item) => item.capacity)),
        ].sort((a, b) => a - b);
      }
    };

    const handleRecharge = async () => {
      state.loading = true;
      let params = {
        type: state.rechargeKey,
      };
      if (
        state.rechargeKey === 0 ||
        state.rechargeKey === 2 ||
        state.rechargeKey === 3
      ) {
        Object.assign(params, state.rechargeData?.option);
      }
      if (state.rechargeKey === 1) {
        Object.assign(params, state.rechargeData?.validityData);
      }
		const villageInfo = await store.dispatch("GetVillageInfo")
		if(villageInfo){
			params.village_id = villageInfo.id
		} else {
			params.village_id = 0
		}
		request
		  .put("/work_ai", "/user/shotstack/recharge/pay", params)
		  .then((res) => {
		    state.loading = false;
		    if (res?.result?.pay_status === "success") {
		      router.push({ name: "MediaBusinessRecord" });
		      message.success("操作成功");
		      return;
		    }
		    if (res?.result?.pay_status === "loading") {
		      state.showMemberShip = true;
		      state.rechargeData.payUrl = res?.result?.pay_url;
		    }
		  })
		  .catch(() => {
		    state.loading = false;
		  });
    };

    const rechargeSelectClick = (item) => {
      state.rechargeSelect = item.id;
      state.btnDisable = false;

      Object.assign(state.rechargeData, {
        option: item,
      });
    };

    getRechargeDetail();

    return {
      ...toRefs(state),
      RAMClick,
      ruleClick,
      blurChange,
      handleClose,
      focusChange,
      validityClick,
      rechargeClick,
      handleRecharge,
      rechargeSelectClick,
    };
  },
});
</script>

<style lang="less" scoped>
.box {
  .content {
    margin-top: 20px;
    border-radius: 16px;
    background: rgba(255, 255, 255, 0.4);
    padding: 24px;
    .recharge-type {
      margin: 10px 0;
      .recharge-item {
        margin-right: 16px;
        width: 220px;
        height: 100px;
        cursor: pointer;
        overflow: hidden;
        padding: 16px;
        border-radius: 10px;
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid rgb(229, 231, 235);

        .item-text {
          font-size: 30px;
          font-weight: 700;
          text-align: center;
          .text {
            font-size: 16px;
          }
          .amount {
            color: var(--ss-primary-color);
            font-size: 30px;
          }
          .amount::before {
            content: "￥";
            font-size: 18px;
          }
        }

        .checked {
          width: 40px;
          height: 65px;
          display: flex;
          align-items: center;
          justify-content: center;
          padding-right: 20px;
          color: #fff;
          font-size: 18px;
          position: absolute;
          bottom: -29px;
          right: -13px;
          transform: rotate(53deg);
          background: var(--ss-primary-color);
        }

        &.recharge-bg {
          border: 1px solid var(--ss-primary-color);
        }

        #inputNumber {
          margin-top: 5px;
          text-align: center;
          border: none;
        }
        .input-text {
          transition: all 0.3s;
          color: var(--ss-primary-color);
        }
      }
    }

    .purchase-quantity {
      margin: 10px 0;
    }
    .voucher-number {
      display: flex;
      .voucher-item {
        width: 220px;
        height: 100px;
        margin-right: 16px;
        margin-bottom: 16px;
        cursor: pointer;
        overflow: hidden;
        padding: 16px;
        border-radius: 10px;
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid rgb(229, 231, 235);
        font-size: 26px;
        font-weight: 700;
        &.voucher-border {
          border: 1px solid var(--ss-primary-color);
        }
        .checked {
          width: 40px;
          height: 65px;
          display: flex;
          align-items: center;
          justify-content: center;
          padding-right: 20px;
          color: #fff;
          font-size: 18px;
          position: absolute;
          bottom: -29px;
          right: -13px;
          transform: rotate(53deg);
          background: var(--ss-primary-color);
        }
      }

      .minus {
        width: 37px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-right: 1px solid rgb(224, 224, 230);
        &:hover {
          color: var(--ss-primary-color);
          cursor: pointer;
        }
      }
      .add {
        width: 37px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-left: 1px solid rgb(224, 224, 230);
        &:hover {
          color: var(--ss-primary-color);
          cursor: pointer;
        }
      }
    }

    .period-validity {
      .validity-list {
        .item {
          height: 40px;
          border: 1px solid rgb(224, 224, 230);
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.3s;
          padding: 0 20px;
          &.item-broder {
            color: var(--ss-primary-color);
            border: 1px solid var(--ss-primary-color);
          }
          &:hover {
            color: var(--ss-primary-color);
          }
        }
      }
    }
  }
  :deep(.ant-input-number-input) {
    text-align: center;
  }
}
</style>
